//
//  CountDownButton.m
//  HZBus
//
//  Created by user on 16/10/28.
//  Copyright © 2016年 user. All rights reserved.
//

#import "CountDownButton.h"
#import "CountDownTask.h"
@interface CountDownButton ()

@end

@implementation CountDownButton

/** 单例对象 */
+ (instancetype)standardCountDown{
    static CountDownButton *btnDefault = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        btnDefault = [[CountDownButton alloc] init];
        btnDefault.pool = [[NSOperationQueue alloc] init];
    });
    return btnDefault;
}

- (void)scheduledCountDownWithKey:(NSString *)aKey timeInterval:(NSTimeInterval)timeInterval create:(BOOL)isCreate countingDown:(countDownBlock)countingDown finished:(countDownBlock)finished{
    
    if (timeInterval > 120) {
        [SVProgressHUD showErrorWithStatus:NSLocalString(@"倒计时不能大于120秒")];
        return;
    }
    
    if (_pool.operations.count > 20) { //最多20个并发线程
        return;
    }
    
    CountDownTask *task = nil;
    
    //查询该名字的任务是否存在
    for (CountDownTask *alsoTask in _pool.operations) {
        if ([alsoTask.operationName isEqualToString:aKey]) {
            task = alsoTask;
            break;
        }
    }
    //存在,继续跑定时器
    if (task != nil) {
        task.countingDownBlock = countingDown;
        task.finishedBlock = finished;
        if (countingDown) {
            countingDown(task.leftTimeInterval);
        }
        
    }else {//不存在,如果 允许创建(isCreate),则创建定时器线程,否则返回
        if (!isCreate) {
            return;
        }
        task = [[CountDownTask alloc] init];
        task.leftTimeInterval = timeInterval;
        task.countingDownBlock = countingDown;
        task.finishedBlock = finished;
        task.operationName = aKey;
        
        [_pool addOperation:task];
    }
}

- (void)removeTaskWithKey:(NSString *)aKey {
    //查询该名字的任务是否存在
    for (CountDownTask *alsoTask in _pool.operations) {
        if ([alsoTask.operationName isEqualToString:aKey]) {
            [alsoTask cancel];
            return;
        }
    }
}


@end
